//
//  ZZBaseWebViewController.m
//  OCFrame
//
//  Created by hfzhangzhang on 2017/1/4.
//  Copyright © 2017年 hfzhangzhang. All rights reserved.
//

#import "ZZBaseWebViewController.h"
#import "ZZConstant.h"

@interface ZZBaseWebViewController ()<WKUIDelegate,WKNavigationDelegate>

@property (nonatomic, strong) WKWebView *baseWebView;
@property (strong, nonatomic) UIProgressView *progressView;

@end

@implementation ZZBaseWebViewController

-(void)viewDidLoad{
    [super viewDidLoad];
   [self.baseWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_loadUrl]]];
}

-(WKWebView*)baseWebView{
    if (_baseWebView==nil) {
        //WebView配置
        [self clearCache];
        WKWebViewConfiguration *config = [WKWebViewConfiguration new];
        config.preferences = [WKPreferences new];
        config.preferences.minimumFontSize = 10;
        config.preferences.javaScriptEnabled = YES;
        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        _baseWebView = [[WKWebView alloc]initWithFrame:self.view.frame configuration:config];
        _baseWebView.UIDelegate = self;
        _baseWebView.navigationDelegate =self;
       [self.view addSubview:_baseWebView];
        [self.view insertSubview:_baseWebView belowSubview:self.progressView];
        //添加KVO监听
        [_baseWebView addObserver:self
                       forKeyPath:@"loading"
                          options:NSKeyValueObservingOptionNew
                          context:nil];
        [_baseWebView addObserver:self
                       forKeyPath:@"title"
                          options:NSKeyValueObservingOptionNew
                          context:nil];
        [_baseWebView addObserver:self
                       forKeyPath:@"estimatedProgress"
                          options:NSKeyValueObservingOptionNew
                          context:nil];
    }
    return _baseWebView;
}
- (UIProgressView *)progressView
{
    if(!_progressView)
    {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0,   kHeight_NavBar, kScreen_Width, 20)];
        self.progressView.tintColor = [UIColor blueColor];
        self.progressView.trackTintColor = [UIColor redColor];
        [self.view addSubview:self.progressView];
    }
    return _progressView;
}

#pragma mark - WKUIDelegate代理

#pragma mark - WKNavigationDelegate代理
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    //wkwebview跳转不了AppStore
    if ([webView.URL.absoluteString hasPrefix:@"https://itunes.apple.com"]) {
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        decisionHandler(WKNavigationActionPolicyCancel);
    }
//    WebKit框架对跨域进行了安全性检查限制，不允许跨域，比如从一个 HTTP 页对 HTTPS 发起请求是无效的
//    else if ([webView.URL.scheme isEqualToString:@"https"]){
//        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
//        decisionHandler(WKNavigationActionPolicyCancel);
//    }
    else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}


// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"title"]) {
        self.title = _baseWebView.title;
    }else if([keyPath isEqualToString:@"loading"]){
        NSLog(@"loading");
    }
    else if ([keyPath isEqualToString:@"estimatedProgress"]){
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            self.progressView.hidden = YES;
            [self.progressView setProgress:0 animated:NO];
        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
}

-(void)clearCache{
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        NSSet *types =[NSSet setWithArray:@[WKWebsiteDataTypeDiskCache,WKWebsiteDataTypeMemoryCache,WKWebsiteDataTypeOfflineWebApplicationCache,WKWebsiteDataTypeCookies,WKWebsiteDataTypeSessionStorage,WKWebsiteDataTypeLocalStorage,WKWebsiteDataTypeWebSQLDatabases,WKWebsiteDataTypeIndexedDBDatabases]];
        NSDate *dataFrom = [NSDate date];
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:types modifiedSince:dataFrom completionHandler:^{
            kLog(@"clearCache");
        }];
    }
    else{
        NSString *libraryPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject;
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:nil];
    }
  
}


// 记得取消监听
- (void)dealloc {
    //移除监听
    [_baseWebView removeObserver:self forKeyPath:@"loading"];
    [_baseWebView removeObserver:self forKeyPath:@"title"];
    [_baseWebView removeObserver:self forKeyPath:@"estimatedProgress"];
}


@end
